# -*- coding: utf-8 -*-
# make_response制造返回头
from flask import Blueprint,request,jsonify,make_response,redirect,g
import json
from common.models.User import User
from common.libs.user.UserService import UserService
from common.libs.Helper import ops_render
from application import app,db
from common.libs.UrlManager import UrlManager

route_user = Blueprint( 'user_page',__name__ )

@route_user.route( "/login" ,methods=["GET","POST"])
def login():
    if request.method == "GET":
        return ops_render( "user/login.html" )

    resp ={'code':200,'msg':'登录成功','data':{}}
    req = request.values
    login_name =req['login_name'] if 'login_name' in req else ''
    login_pwd =req['login_pwd'] if 'login_pwd' in req else ''

    # 通过jsonify()方法也是将字典转成json字符串
    if login_name is None or len(login_name) < 1 :
        resp['code']= -1
        resp['msg']="请输入正确的用户名~~"
        return jsonify( resp )

    if login_pwd is None or len(login_pwd) < 1 :
        resp['code']= -1
        resp['msg']="请输入正确的登录密码~~"
        return jsonify( resp )

# flask_alchemy的查询方法
# 第一个login_name是数据库中的，第二个login_name是用户输入login_name的参数
    user_info = User.query.filter_by(login_name = login_name ).first()
    if not user_info:
        resp['code']=-1
        resp['msg']="请输入正确的登录名和密码  -1~~"
        return jsonify(resp)

    # 加密算法  user_info 就是salt
    if user_info.login_pwd != UserService.genePwd( login_pwd,user_info.login_salt):
        resp['code'] = -1
        resp['msg'] = "请输入正确的登录名和密码  -2~~"
        return jsonify(resp)

    # 当用户的状态不等于1，那么就不是正常的登录账号 则无法登陆
    if user_info.status !=1:
        resp['code'] = -1
        resp['msg'] = "您的账号已被禁用，请联系管理员修改账号状态！"
        return jsonify(resp)

    response = make_response( json.dumps( resp))
    # 第二个是授权cookie值 " mooc_food" 第二个是uid 通过井号分割为两部分
    response.set_cookie(app.config['AUTH_COOKIE_NAME'],"%s#%s"%(
        UserService.geneAuthCode(user_info),user_info.uid), 60 * 60 * 24 * 120) # 保存120天

    # return "%s - %s" %(login_name,login_pwd)  写代码测试时候用
    return response

@route_user.route( "/edit",methods=["GET","POST"])
def edit():
    if request.method == "GET":
        return ops_render( "user/edit.html" ,{ 'current':'edit' })

    # 定义统一的回滚值 json的code为200  msg默认值  data是json的
    resp ={'code':200,'msg':'操作成功~','data':{} }
    req =request.values
    nickname =req['nickname'] if 'nickname' in req else ''
    email = req['email'] if 'email' in req else ''

    if nickname is None or len( nickname ) < 1:
        resp['code']=-1
        resp['msg'] = "请输入复核规范的姓名"
        # 进行json格式的转换
        return jsonify(resp)

    if email is None or len( email ) < 1:
        resp['code']=-1
        resp['msg'] = "请输入复核规范的邮箱"
        # 进行json格式的转换
        return jsonify(resp)

    user_info =g.current_user
    user_info.nickname =nickname
    user_info.email = email

    db.session.add(user_info)
    # 统一提交
    db.session.commit()
    #更改成功
    return jsonify(resp)

@route_user.route( "/reset-pwd",methods=["GET","POST"] )
def resetPwd():
    if request.method == "GET":
        # 提交完数据
        return ops_render( "user/reset_pwd.html" ,{ 'current':'reset-pwd' })
#     开始更改数据
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    req = request.values

    old_password = req['old_password'] if 'old_password' in req else ''
    new_password = req['new_password'] if 'new_password' in req else ''

    # 修改
    user_info=g.current_user
    db_user_info =User.query.filter_by(uid=user_info.uid).first()
    old_md5_password=UserService.genePwd(old_password,db_user_info.login_salt)
    db_user_info_pwd =db_user_info.login_pwd
    if old_md5_password != db_user_info_pwd:
        resp['code'] = -1
        resp['msg'] = "原始密码错误，请修改~"
        return jsonify(resp)

    if old_password is None or len( old_password)  < 6:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的原密码~"
        # 进行json格式的转换
        return jsonify(resp)

    if new_password is None or len( new_password) < 6:
        resp['code'] = -1
        resp['msg'] = "请输入复合规范的新密码~"
        # 进行json格式的转换
        return jsonify(resp)

    if old_password == new_password:
        resp['code'] = -1
        resp['msg'] = "新密码和原密码不能相同，请重新输入！"
        # 进行json格式的转换
        return jsonify(resp)

#     进行密码的更改  用当前的current_user取出的对象
    user_info = g.current_user
    # 这的密码不是原始的 是经过加密算法进行加密的
    # 原来加密算法卸载了userServicede genePwd中，我们把new密码放入其中
    user_info.login_pwd = UserService.genePwd(new_password,user_info.login_salt)
  
    # 将数据插入数据库中
    db.session.add(user_info)
    # 统一提交
    db.session.commit()
    # cookie的刷新
    response = make_response(json.dumps(resp))
    # 第二个是授权cookie值 " mooc_food" 第二个是uid 通过井号分割为两部分
    response.set_cookie(app.config['AUTH_COOKIE_NAME'], "%s#%s" % (
        UserService.geneAuthCode(user_info), user_info.uid), 60 * 60 * 24 * 120)  # 保存120天

    # return "%s - %s" %(login_name,login_pwd)  写代码测试时候用
    return response
    # 统一返回
    # return jsonify(resp)

# 登出功能
@route_user.route("/logout")
def logout():
    response = make_response(redirect(UrlManager.buildUrl("/user/login")))
    response.delete_cookie(app.config['AUTH_COOKIE_NAME'])
    return response